<template>
  <div class="image-management">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="title">镜像管理</span>
        <div class="header-operations">
          <el-button-group>
            <el-button type="primary" size="small" icon="el-icon-refresh" @click="refreshImages">刷新</el-button>
            <el-button type="success" size="small" icon="el-icon-upload2" @click="showUploadDialog">上传镜像</el-button>
            <el-button type="info" size="small" icon="el-icon-download" @click="showPullImageDialog">拉取镜像</el-button>
          </el-button-group>
        </div>
      </div>

      <!-- Image Statistics -->
      <el-row :gutter="20" class="statistics-row">
        <el-col :span="6">
          <el-card shadow="hover" class="statistic-card">
            <div class="statistic-content">
              <div class="statistic-icon">
                <i class="el-icon-picture"></i>
              </div>
              <div class="statistic-info">
                <div class="statistic-label">总镜像数</div>
                <div class="statistic-value">{{ totalImages }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="statistic-card">
            <div class="statistic-content">
              <div class="statistic-icon">
                <i class="el-icon-folder"></i>
              </div>
              <div class="statistic-info">
                <div class="statistic-label">本地镜像</div>
                <div class="statistic-value">{{ localImages }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="statistic-card">
            <div class="statistic-content">
              <div class="statistic-icon">
                <i class="el-icon-cloudy"></i>
              </div>
              <div class="statistic-info">
                <div class="statistic-label">远程镜像</div>
                <div class="statistic-value">{{ remoteImages }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover" class="statistic-card">
            <div class="statistic-content">
              <div class="statistic-icon">
                <i class="el-icon-coin"></i>
              </div>
              <div class="statistic-info">
                <div class="statistic-label">总存储空间</div>
                <div class="statistic-value">{{ totalSize }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- Search and Filter -->
      <el-row :gutter="20" class="search-filter-row">
        <el-col :xs="24" :sm="12" :md="8" :lg="10">
          <el-input
            v-model="searchQuery"
            placeholder="搜索镜像名称或标签"
            prefix-icon="el-icon-search"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
          >
            <el-select v-model="filterType" slot="append" placeholder="类型" @change="handleSearch">
              <el-option label="全部" value=""></el-option>
              <el-option label="本地" value="local"></el-option>
              <el-option label="远程" value="remote"></el-option>
            </el-select>
          </el-input>
        </el-col>
      </el-row>

      <!-- Image List Table -->
      <el-table
        :data="filteredImages"
        style="width: 100%"
        v-loading="loading"
        @row-click="handleRowClick"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="镜像名称/ID" min-width="180" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <div class="repository-name">
              <el-tooltip :content="row.id" placement="top">
              </el-tooltip>
              <div class="name-container">
                <span class="name">{{ row.name }}</span>

              </div>
              <div class="name-container">
                <span class="name">{{ row.id }}</span>

              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120" show-overflow-tooltip>
          <template slot-scope="{ row }">
            <el-tag
              :type="row.status === 'active' ? 'success' : 'info'"
              size="small"
              effect="plain"
            >
              {{ getImagesStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="__os_version" label="标签" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="__image_size" label="大小" width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ formatSize(scope.row.__image_size) }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" show-overflow-tooltip></el-table-column>
        <el-table-column prop="virtual_env_type" label="类型" width="180">
          <template slot-scope="scope">
            <el-tag :type="scope.row.virtual_env_type === 'FusionCompute' ? 'success' : 'info'">
              {{ scope.row.virtual_env_type === 'FusionCompute' ? 'BMS系统盘镜像(ARM)' : '远程' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
<!--          <template slot-scope="scope">-->
<!--            <el-button @click.stop="handlePush(scope.row)" type="text" size="small">推送</el-button>-->
<!--            <el-button @click.stop="handlePull(scope.row)" type="text" size="small" v-if="scope.row.type === 'remote'">拉取</el-button>-->
<!--            <el-button @click.stop="handleDelete(scope.row)" type="text" size="small">删除</el-button>-->
<!--          </template>-->
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalImages">
        </el-pagination>
      </div>
    </el-card>

    <!-- Image Details Dialog -->
    <el-dialog title="镜像详情" :visible.sync="detailsVisible" width="60%">
      <el-descriptions :column="2" border v-if="selectedImage">
        <el-descriptions-item label="镜像名称">{{ selectedImage.name }}</el-descriptions-item>
        <el-descriptions-item label="标签">{{ selectedImage.__os_type }}</el-descriptions-item>
        <el-descriptions-item label="镜像ID">{{ selectedImage.id }}</el-descriptions-item>
        <el-descriptions-item label="大小">{{ formatSize(selectedImage.__image_size) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ selectedImage.created_at }}</el-descriptions-item>
        <el-descriptions-item label="类型">
          <el-tag :type="selectedImage.type === 'local' ? 'success' : 'info'">
            {{ selectedImage.type === 'local' ? '本地' : '远程' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="摘要" :span="2">{{ selectedImage.file }}</el-descriptions-item>
        <el-descriptions-item label="操作系统" :span="2">{{ selectedImage.__os_version }}</el-descriptions-item>
        <el-descriptions-item label="架构">{{ selectedImage.__os_bit }}</el-descriptions-item>
        <el-descriptions-item label="作者">{{ selectedImage.author }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- Pull Image Dialog -->
    <el-dialog title="拉取镜像" :visible.sync="pullImageVisible" width="40%">
      <el-form :model="pullImageForm" label-width="100px">
        <el-form-item label="镜像名称">
          <el-input v-model="pullImageForm.name" placeholder="例如：nginx"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="pullImageForm.tag" placeholder="例如：latest"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pullImageVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePullImage">确定</el-button>
      </span>
    </el-dialog>

    <!-- Upload Image Dialog -->
    <el-dialog title="上传本地镜像" :visible.sync="uploadImageVisible" width="40%">
      <el-form :model="uploadImageForm" label-width="100px">
        <el-form-item label="镜像文件">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :http-request="handleImageUpload"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传tar格式的Docker镜像文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="镜像名称">
          <el-input v-model="uploadImageForm.name" placeholder="例如：my-app"></el-input>
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="uploadImageForm.tag" placeholder="例如：v1.0"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="uploadImageVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUploadImage" :disabled="!uploadImageForm.file">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {listOrderinstance, lookmirror} from "@/api/resell/orderinstance";

export default {
  name: 'ImageManagement',
  data() {
    return {
      loading: false,
      searchQuery: '',
      filterType: '',
      currentPage: 1,
      pageSize: 10,
      detailsVisible: false,
      selectedImage: null,
      pullImageVisible: false,
      pullImageForm: {
        name: '',
        tag: ''
      },
      uploadImageVisible: false,
      uploadImageForm: {
        name: '',
        tag: '',
        file: null
      },
      fileList: [],
      images: [
        { id: '1', name: 'nginx', tag: 'latest', size: '133MB', createdAt: '2024-04-28 10:00:00', type: 'local', digest: 'sha256:123...', os: 'linux', architecture: 'amd64', author: 'NGINX Docker Maintainers' },
        { id: '2', name: 'redis', tag: '6.0', size: '104MB', createdAt: '2024-04-27 15:30:00', type: 'remote', digest: 'sha256:456...', os: 'linux', architecture: 'amd64', author: 'Redis' },
        { id: '3', name: 'postgres', tag: '13', size: '314MB', createdAt: '2024-04-26 09:15:00', type: 'local', digest: 'sha256:789...', os: 'linux', architecture: 'amd64', author: 'PostgreSQL' },
        { id: '4', name: 'mysql', tag: '8.0', size: '420MB', createdAt: '2024-04-25 12:45:00', type: 'remote', digest: 'sha256:012...', os: 'linux', architecture: 'amd64', author: 'MySQL' },

        // 添加更多示例数据...
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        resourceId: null,
        resourceName: null,
        regionCode: null,
        serviceTypeCode: null,
        resourceTypeCode: null,
        resourceSpecCode: null,
        serviceTypeName: null,
        resourceTypeName: null,
        projectId: null,
        productId: null,
        parentResourceId: null,
        isMainResource: null,
        status: null,
        effectiveTime: null,
        expireTime: null,
        expirePolicy: null,
        productSpecDesc: null,
        specSize: null,
        specSizeMeasureId: null,
        updateTime1: null,
        enterpriseProject: null,
        projectsId: null,
        projectsName: null,
        other1: null,
        other2: null,
        other3: null,
        other4: null,
        other5: null,
        puserid: null,//客户id
        pusertype: '07',//客户07  经销商06
        exptype:null,//到期天数类型1-30天，2-90天
        scode:1,
        ucode: "QIYUNHUI",
        ucodeiam: "zdx-01",
        upsw: "HWY@2025"
      },
    };
  },
  computed: {
    filteredImages() {
      let filtered = this.images;
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        filtered = filtered.filter(image =>
          image.name.toLowerCase().includes(query) ||
          image.tag.toLowerCase().includes(query)
        );
      }
      if (this.filterType) {
        filtered = filtered.filter(image => image.type === this.filterType);
      }
      return filtered;
    },
    totalImages() {
      return this.filteredImages.length;
    },
    localImages() {
      return this.images.filter(image => image.type === 'local').length;
    },
    remoteImages() {
      return this.images.filter(image => image.type === 'remote').length;
    },
    totalSize() {
      const totalBytes = this.images.reduce((acc, image) => {
        const size = parseFloat(image.size);
        return acc + (isNaN(size) ? 0 : size);
      }, 0);
      return this.formatSize(totalBytes);
    }
  },
  created() {
    this.refreshImages();
  },
  methods: {
    refreshImages() {
      this.loading = true;
      // 模拟API调用
      const userType ='07';
      this.queryParams.puserid = this.$store.state.user.userId;
      this.queryParams.pusertype=userType;
      // console.log(this.queryParams)
      lookmirror(this.queryParams).then(response => {
        console.log(response)
        this.images =response.data
        this.loading = false;
        this.$message.success('镜像列表已刷新');
      });
    },
    handleSearch() {
      this.currentPage = 1;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleRowClick(row) {
      this.selectedImage = row;
      this.detailsVisible = true;
    },
    handlePush(image) {
      this.$confirm(`确定要推送镜像 ${image.name}:${image.tag} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: `镜像 ${image.name}:${image.tag} 推送任务已启动`
        });
      }).catch(() => {});
    },
    handlePull(image) {
      this.$confirm(`确定要拉取镜像 ${image.name}:${image.tag} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: `镜像 ${image.name}:${image.tag} 拉取任务已启动`
        });
      }).catch(() => {});
    },
    handleDelete(image) {
      this.$confirm(`确定要删除镜像 ${image.name}:${image.tag} 吗？此操作不可逆。`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        this.images = this.images.filter(i => i.id !== image.id);
        this.$message({
          type: 'success',
          message: `镜像 ${image.name}:${image.tag} 已成功删除`
        });
      }).catch(() => {});
    },
    getImagesStatusName(status)
    {
      if (!status) return '未知';
      const statusMap = {
        'active': '正常',
        'creating': '创建中',
        'error': '错误',
        'deleting': '删除中',
        'deleted': '已删除'
      };

      return statusMap[status] || status;
    },
    showPullImageDialog() {
      this.pullImageVisible = true;
    },
    handlePullImage() {
      if (!this.pullImageForm.name) {
        this.$message.error('请输入镜像名称');
        return;
      }
      this.$message({
        type: 'success',
        message: `开始拉取镜像 ${this.pullImageForm.name}:${this.pullImageForm.tag || 'latest'}`
      });
      this.pullImageVisible = false;
      this.pullImageForm = { name: '', tag: '' };
    },
    showUploadDialog() {
      this.uploadImageVisible = true;
    },
    handleImageUpload(params) {
      this.uploadImageForm.file = params.file;
    },
    handleExceed() {
      this.$message.warning('只能上传一个文件');
    },
    handleUploadImage() {
      if (!this.uploadImageForm.name || !this.uploadImageForm.file) {
        this.$message.error('请填写镜像名称并选择文件');
        return;
      }
      // 模拟上传过程
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        this.$message.success(`镜像 ${this.uploadImageForm.name}:${this.uploadImageForm.tag || 'latest'} 上传成功`);
        this.uploadImageVisible = false;
        this.uploadImageForm = { name: '', tag: '', file: null };
        this.fileList = [];
        // 在这里可以添加新上传的镜像到列表中
      }, 2000);
    },
    formatSize(bytes) {
      if (!bytes || bytes === 0) return '0 GB';
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(bytes) / Math.log(1024));
      return parseFloat((bytes / Math.pow(1024, i)).toFixed(2)) + ' ' + sizes[i];
    }
  }
};
</script>

<style scoped>
.image-management {
  padding: 10px;
}

.box-card {
  margin-bottom: 10px;
}

.header-operations {
  float: right;
}

.statistics-row {
  margin-bottom: 20px;
}

.statistic-card {
  height: 100px;
}

.statistic-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.statistic-icon {
  font-size: 32px;
  margin-right: 15px;
  color: #409EFF;
}

.statistic-info {
  display: flex;
  flex-direction: column;
}

.statistic-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 5px;
}

.statistic-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.search-filter-row {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .header-operations {
    float: none;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
  }

  .statistics-row .el-col {
    margin-bottom: 10px;
  }

  .search-filter-row .el-col {
    margin-bottom: 10px;
  }

  .pagination-container {
    text-align: center;
  }
}
</style>
